package llutyo.andcrypt;

/*Copyright 2012 Akos Ludanyi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Log;

public class CryptoHelper {
	final static private String TAG = "crypt";
	
	final static public String HASH_ALG = "SHA-256"; 
	final static public String CRYPT_ALG = "AES/CBC/PKCS5Padding";
	final static public int KEY_SIZE = 256 / 8;
	final static public int BLOCK_SIZE = 128 / 8;
	
	public static byte[] getRandomKey() {
		Random rnd = new Random();
		byte[] key = new byte[KEY_SIZE];
		rnd.nextBytes(key);
		return key;
	}
	
	public static byte[] hashData(byte[] data) {
		try {
			MessageDigest md = MessageDigest.getInstance(HASH_ALG);
			return md.digest(data);
		}
		catch(NoSuchAlgorithmException e) {
			Log.e(TAG, "Hash not found.", e);
		}
		return null;
	}
	
	public static byte[] getStaticSalt() {
		SecureRandom rnd = new SecureRandom(new byte[]{72, 21, 43, 4, 24});
		byte[] ret = new byte[20];
		rnd.nextBytes(ret);
		return ret;
	}
	
	public static byte[] passwordToKey(String pwd, byte[] salt) {
		try {
			SecretKeyFactory f = SecretKeyFactory.getInstance("PBEWITHSHA256AND128BITAES-CBC-BC");
			KeySpec ks = new PBEKeySpec(pwd.toCharArray(), salt, 10, 128);
			SecretKey s = f.generateSecret(ks);
			
			byte[] genKey = s.getEncoded();
			byte[] key = new byte[KEY_SIZE];
			System.arraycopy(genKey, 0, key, 0, Math.min(genKey.length, KEY_SIZE));
			return key;
		}
		catch(Exception e) {
			Log.e(TAG, "Key generation failed.", e);
		}
		
		return null;
	}
	
	public static byte[] encrypt(byte [] data, byte[] rawKey, byte[] iv) {
		try {
			byte[] hash = hashData(data);
			byte[] tmp = new byte[data.length + hash.length];
			
			System.arraycopy(data, 0, tmp, 0, data.length);
			System.arraycopy(hash, 0, tmp, data.length, hash.length);
			data = tmp;
			
			
			SecretKey key = new SecretKeySpec(rawKey, "AES");
			
			if(iv == null) {
				iv = new byte[BLOCK_SIZE];
				Arrays.fill(iv, (byte)0);
			}
			AlgorithmParameterSpec ivParam = new IvParameterSpec(iv);
			
			Cipher cipher = Cipher.getInstance(CRYPT_ALG);
			
			cipher.init(Cipher.ENCRYPT_MODE, key, ivParam);
			return cipher.doFinal(data);
		}
		catch(Exception e) {
			Log.e(TAG, "Encrypter not found.", e);
		}
		
		return null;
	}

	public static byte[] decrypt(byte [] data, byte[] rawKey, byte[] iv) {
		try {
			SecretKey key = new SecretKeySpec(rawKey, "AES");
			if(iv == null) {
				iv = new byte[BLOCK_SIZE];
				Arrays.fill(iv, (byte)0);
			}
			
			
			Cipher cipher = Cipher.getInstance(CRYPT_ALG);
			cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
			
			byte[] res = cipher.doFinal(data);
			
			MessageDigest md = MessageDigest.getInstance(HASH_ALG);
			int len = md.getDigestLength();
			
			byte [] original = new byte[res.length - len];
			System.arraycopy(res, 0, original, 0, original.length);
			
			byte[] hash = md.digest(original);
			
			for(int i = 0; i < len; i++) {
				if(hash[i] != res[original.length + i]) {
					throw new Exception("Data corrupted!");
				}
			}
			
			return original;
		}
		catch(Exception e) {
			Log.e(TAG, "Encrypter not found.", e);
		}
		
		return null;
	}
}